package com.os.meituan.service.sec;


import com.os.meituan.common.DateClass;
import com.os.meituan.common.PubClass;
import com.os.meituan.common.SecurityClass;
import com.os.meituan.common.StringClass;
import com.os.meituan.model.pomodel.ILoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CommonAuthService {

    @Value("${sysName}")
    private String g_sysName;

    private final String g_securityKey = "20191223132400"; // 加密密钥
    private final String g_loginUserSessionKey = "loginUser"; // sessionid
    private final String g_tokenHasChk = "chk_";
    private final String g_tokenHasSessionCacheKey = "_hasSession";
    private final String g_decryptToken = "decrypt_";

    //    @Resource
//    private HttpSession session;
    @Resource
    private PubClass pubclass;
    @Resource
    private SYS_RoleService sys_roleService;


    public void setCurrentUser(ILoginUser info) {
        List<String> list = new ArrayList<>();
        list.add(String.valueOf(info.getLoginUserID()));
        list.add(info.getLoginUserType());
        list.add(DateClass.getCurDate());
        list.add(g_sysName);
        String token = SecurityClass.encryptAES(StringClass.join(list, "_"), g_securityKey);
        info.setLoginUserToken(token);

        // 获得用户有那些角色权限
        //REVIEW 这里可能需要根据登录用户类型，确定id是否是long还是string类型

        setLoginUserRoles(info);

//        setLoginUserAuthorities(info);
//        session.invalidate(); // 使之前的匿名session失效 固定SessionID的漏洞（详见《黑客攻防技术宝典-web实战》第七章）
////        session.setMaxInactiveInterval(28800);
////        session.setAttribute(g_loginUserSessionKey, token);

//        var json=JsonClass.toJSON(info.getLoginUserGrantedAuthority());
//      var listp=  JSON.parseArray(json,GrantedAuthority.class);
//        List<SimpleGrantedAuthority> listp= JsonClass.fromJSON(json,new TypeReference<List<SimpleGrantedAuthority>>(){});
        pubclass.setCache(token, info, 60 * 12);


    }

//    private void setLoginUserAuthorities(ILoginUser userInfo) {
//        Set<SimpleGrantedAuthority> authList = new HashSet<SimpleGrantedAuthority>();
//        if (userInfo.getLoginUserRolesKey() != null) {
//            userInfo.getLoginUserRolesKey().forEach(q -> authList.add(new SimpleGrantedAuthority(q)));
//        }
//
//        if (userInfo.getLoginUserRolesPower() != null) {
//            userInfo.getLoginUserRolesPower().forEach(q -> authList.add(new SimpleGrantedAuthority(q)));
//        }
//
//        userInfo.setLoginUserGrantedAuthority(authList);
//    }
public void setLoginUserRoles(ILoginUser info) {

    // 获得用户配置好的权限
    var listRolesKey = sys_roleService.getEnableRolesKeysByUserId(info.getLoginUserID());
    var listRolesPower = sys_roleService.getEnableRolesPowerListByUserId(info.getLoginUserID());

    // 添加默认权限角色
    listRolesKey.add("COMMONT_ROLE"); // commont这英文是打错了，多了一个t
    List<String> rolePower = sys_roleService.getRolePowerByRoleKey("COMMONT_ROLE");
    if (rolePower != null) {
        listRolesPower.addAll(rolePower);
    }

    if(StringClass.hasValue(info.getLoginUserType())) {
        // 添加用户不同身份默认权限角色
        var commonRoleKeyForUserType = "";
        switch (info.getLoginUserType().toLowerCase()) {
            case "local":
                commonRoleKeyForUserType = "COMMONT_ROLE_MingJing"; // 民警通用权限
                break;
            case "fujing":
                commonRoleKeyForUserType = "COMMONT_ROLE_FuJing";  // 辅警通用权限
                break;
            case "caizhengzhigong":
                commonRoleKeyForUserType = "COMMONT_ROLE_CaiZhengZhiGong"; // 财政职工通用权限
                break;
            case "hetonggong":
                commonRoleKeyForUserType = "COMMONT_ROLE_HeTongGong"; // 合同工通用权限
                break;
        }

        if (StringClass.hasValue(commonRoleKeyForUserType)) {
            listRolesKey.add(commonRoleKeyForUserType);
            List<String> rolePowerForUserType = sys_roleService.getRolePowerByRoleKey(commonRoleKeyForUserType);
            if (rolePowerForUserType != null) {
                listRolesPower.addAll(rolePowerForUserType);
            }
        }
    }

    info.setLoginUserRolesKey(StringClass.join(listRolesKey, ","));
    info.setLoginUserRolesPower(StringClass.join(listRolesPower.stream().distinct().collect(Collectors.toList()), ","));


}


}
